package keeto.com.vn.classified.ui;


import java.util.ArrayList;

import keeto.com.vn.classified.adapter.AdapterProductViewAll;
import keeto.com.vn.classified.adapter.SubProductAdapter;
import keeto.com.vn.classified.core.ClassifiedCore;
import keeto.com.vn.classified.core.ClassifiedListener;
import keeto.com.vn.classified.database.BuiltinService;
import keeto.com.vn.classified.database.BuiltinServiceManager;
import keeto.com.vn.classified.network.IProtocol;
import keeto.com.vn.classified.network.entity.ListItemEntity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.androidquery.AQuery;
import com.androidquery.util.AQUtility;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

public class FavoritesActivity extends Activity implements OnRefreshListener<ListView>, OnClickListener {
	public static final String ACTION_FAVORITES = "Favorites";
	public static final String ACTION_POSTED = "Posted";
	public static final String ACTION_HISTORY = "History";

	private String Action;
	private ImageButton btnBack;
	private TextView tvTitle;
	private ImageView btnSearch;
	private PullToRefreshListView refreshListView;
	private ProgressBar mBar;
	private AdapterProductViewAll productsAdapter;
	private ArrayList<ListItemEntity> ArrayList = new ArrayList<ListItemEntity>();
	private int PageLimit = 10;
	private int PageNumber =1;
	private BuiltinServiceManager manager;
	private BuiltinService service;
	private String UserName;
	private String UserId;
	private String AuthKey;
	private MyHandBookListener mListener = new MyHandBookListener();
	private ArrayList<String> arrHistoryID = new ArrayList<String>();
	private AQuery mQuery;

	public static void actionViewFavorites(Context context) {
		Intent i = new Intent(context, FavoritesActivity.class);
		i.setAction(ACTION_FAVORITES);
		context.startActivity(i);
	}
	public static void actionViewPosted(Context context) {
		Intent i = new Intent(context, FavoritesActivity.class);
		i.setAction(ACTION_POSTED);
		context.startActivity(i);
	}
	public static void actionViewHistory(Context context) {
		Intent i = new Intent(context, FavoritesActivity.class);
		i.setAction(ACTION_HISTORY);
		context.startActivity(i);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ia_favorites_view);
		manager = BuiltinServiceManager.getInstance(this);
		service = manager.getBuitinService();
		mQuery = new AQuery(this);
		if (service != null){
			UserName = service.getUserName();
			UserId = service.getUserId();
			AuthKey = service.getAuthKey();
			initUIComponent();
			onNewIntent(getIntent());
		}
	}
	private void initUIComponent(){
		btnBack = (ImageButton)findViewById(R.id.btn_sub_title_back);
		tvTitle = (TextView)findViewById(R.id.tv_sub_title_text);
		btnSearch = (ImageView)findViewById(R.id.btn_sub_title_search_home);
		refreshListView = (PullToRefreshListView)findViewById(R.id.lv_favorites);
		mBar = (ProgressBar)findViewById(R.id.pb_load);
		productsAdapter = new AdapterProductViewAll(this, ArrayList,mQuery);
		refreshListView.setAdapter(productsAdapter);
		productsAdapter.notifyDataSetChanged();
		mBar.setVisibility(View.VISIBLE);
		refreshListView.setOnRefreshListener(this);
		btnBack.setOnClickListener(this);
		btnSearch.setVisibility(View.GONE);
	}


	@Override
	protected void onNewIntent(Intent intent) {
		// TODO Auto-generated method stub
		super.onNewIntent(intent);
		Action = intent.getAction();
		if (Action.equals(ACTION_FAVORITES)){
			tvTitle.setText(FavoritesActivity.this.getResources().getString(R.string.menu_bar_interst));
			ClassifiedCore.getInstance(FavoritesActivity.this).taskGetMyHandbook(mListener, 1, UserName, PageNumber, PageLimit, AuthKey, UserId,null);
		}else if (Action.equals(ACTION_POSTED)){
			tvTitle.setText(FavoritesActivity.this.getResources().getString(R.string.menu_bar_posted));

			ClassifiedCore.getInstance(FavoritesActivity.this).taskGetMyHandbook(mListener, 2, UserName, PageNumber, PageLimit, AuthKey, UserId,null);
		}else if (Action.equals(ACTION_HISTORY)){
			tvTitle.setText(FavoritesActivity.this.getResources().getString(R.string.menu_bar_history));
			arrHistoryID.clear();
			arrHistoryID = manager.getproductHistory();
			StringBuilder builder = new StringBuilder();
			builder.append("[");
			for (int i = 0; i< arrHistoryID.size();i++){
				builder.append("\"");
				builder.append(arrHistoryID.get(i).toString());
				builder.append("\",");
			}
			String listid = builder.toString().substring(0, builder.length() - 1) + "]";
			ClassifiedCore.getInstance(FavoritesActivity.this).taskGetMyHandbook(mListener, 3, UserName, PageNumber, PageLimit, AuthKey, UserId,listid);
		}
	}
	@Override
	public void onRefresh(final PullToRefreshBase<ListView> refreshView) {
		// TODO Auto-generated method stub
		if (PageNumber >0){
			if (refreshView.getCurrentMode() == Mode.PULL_FROM_START){
				PageNumber = 1;
				ArrayList.clear();
				productsAdapter.notifyDataSetChanged();
			}
			mBar.setVisibility(View.VISIBLE);
			if (Action.equals(ACTION_FAVORITES)){
				ClassifiedCore.getInstance(FavoritesActivity.this).taskGetMyHandbook(mListener, 1, UserName, PageNumber, PageLimit, AuthKey, UserId,null);
			}else if (Action.equals(ACTION_POSTED)){
				ClassifiedCore.getInstance(FavoritesActivity.this).taskGetMyHandbook(mListener, 2, UserName, PageNumber, PageLimit, AuthKey, UserId,null);
			}else if (Action.equals(ACTION_HISTORY)){
				arrHistoryID.clear();
				arrHistoryID = manager.getproductHistory();
				StringBuilder builder = new StringBuilder();
				builder.append("[");
				for (int i = 0; i< arrHistoryID.size();i++){
					builder.append("\"");
					builder.append(arrHistoryID.get(i).toString());
					builder.append("\",");
				}
				String listid = builder.toString().substring(0, builder.length() - 1) + "]";
				ClassifiedCore.getInstance(FavoritesActivity.this).taskGetMyHandbook(mListener, 3, UserName, PageNumber, PageLimit, AuthKey, UserId,listid);
			}
		}else{
			new Handler().post(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					refreshView.onRefreshComplete();
					mBar.setVisibility(View.GONE);
				}
			});
		}

	}

	class MyHandBookListener extends ClassifiedListener{
		@Override
		public void finishGetMyhandBook(final int returnCode,
				final ArrayList<ListItemEntity> mArrayList, final int pageCount,
				boolean hasmore) {
			// TODO Auto-generated method stub
			super.finishGetMyhandBook(returnCode, mArrayList, pageCount, hasmore);

			runOnUiThread(new Runnable() {
				public void run() {
					mBar.setVisibility(View.GONE);
					if(returnCode==IProtocol.STATUS_CODE_OK_200 && mArrayList != null){
						if (PageNumber < pageCount){
							PageNumber +=1;
						}else{
							PageNumber=-1;
						}
						ArrayList.addAll(mArrayList);
					}
					productsAdapter.notifyDataSetChanged();
					refreshListView.onRefreshComplete();

				}
			});
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_sub_title_back:
			this.finish();
			break;
		default:
			break;
		}
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if(isTaskRoot()){

			long triggerSize = 3000000; 
			long targetSize = 2000000;      
			AQUtility.cleanCacheAsync(this, triggerSize, targetSize);
		}
	}

}
